package com.wstuo.common.sla.service;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.wstuo.common.config.category.dao.IEventCategoryDAO;
import com.wstuo.common.config.category.entity.EventCategory;
import com.wstuo.common.rules.dao.IRulePackageDAO;
import com.wstuo.common.rules.entity.Rule;
import com.wstuo.common.rules.entity.RuleAction;
import com.wstuo.common.rules.entity.RuleConstraint;
import com.wstuo.common.rules.entity.RulePackage;
import com.wstuo.common.rules.entity.RulePattern;
import com.wstuo.common.rules.parser.ProcreationDrlFiles;
import com.wstuo.common.rules.utils.RandomLetters;
import com.wstuo.common.security.dao.IOrganizationDAO;
import com.wstuo.common.security.dao.IOrganizationServicesDAO;
import com.wstuo.common.security.dao.ServiceTimeDAO;
import com.wstuo.common.security.entity.Organization;
import com.wstuo.common.security.entity.OrganizationServices;
import com.wstuo.common.security.entity.ServiceTime;
import com.wstuo.common.security.service.IOrganizationService;
import com.wstuo.common.security.utils.FileEncodeUtils;
import com.wstuo.common.security.utils.LanguageContent;
import com.wstuo.common.sla.dao.ISLAContractDAO;
import com.wstuo.common.sla.dao.ISLARuleDAO;
import com.wstuo.common.sla.dto.SLAContractDTO;
import com.wstuo.common.sla.dto.SLAContractQueryDTO;
import com.wstuo.common.sla.entity.SLAContract;
import com.wstuo.common.sla.entity.SLARule;
import com.wstuo.common.dto.PageDTO;
import com.wstuo.common.exception.ApplicationException;
import com.wstuo.common.file.csv.CSVReader;
import com.wstuo.common.file.csv.CSVWriter;
import com.wstuo.common.util.StringUtils;
import com.wstuo.common.util.TimeUtils;

/**
 * SLA业务类.
 * 
 * @author QXY
 */
public class SLAContractService implements ISLAContractService {
	private static final Logger LOGGER = Logger
			.getLogger(SLAContractService.class);
	@Autowired
	private ISLAContractDAO slaContractDAO;
	@Autowired
	private IOrganizationServicesDAO organizationServicesDAO;
	@Autowired
	private IRulePackageDAO rulePackageDAO;
	@Autowired
	private IOrganizationDAO organizationDAO;
	@Autowired
	private IEventCategoryDAO eventCategoryDAO;
	@Autowired
	private ISLARuleDAO slaRuleDAO;
	private ProcreationDrlFiles procreationDrlFiles = new ProcreationDrlFiles();
	@Autowired
	private IOrganizationService organizationService;
	@Autowired
	private ServiceTimeDAO serviceTimeDAO;
	/**
	 * dto 转成 实体
	 * @param dto 
	 * @param entity
	 */
	private void dto2entity(SLAContractDTO dto, SLAContract entity) {

		try {
			if (dto.getIsDefault()) {
				List<SLAContract> lis = slaContractDAO
						.findBy("isDefault", true);
				for (SLAContract sc : lis) {
					sc.setIsDefault(false);
				}
			}
			BeanUtils.copyProperties(entity, dto);

		} catch (Exception ex) {
			throw new ApplicationException(ex);
		}
	}

	/**
	 * entity2dto Method
	 * 
	 * @param entity
	 * @param dto
	 */
	private void entity2dto(SLAContract entity, SLAContractDTO dto) {

		try {

			BeanUtils.copyProperties(dto, entity);
			if (entity.getServiceOrg() != null) {

				dto.setServiceOrgNo(entity.getServiceOrg().getOrgNo());
				dto.setServiceOrgName(entity.getServiceOrg().getOrgName());
			}
			if (entity.getByServiceOrg() != null) {
				Long[] byOrgNos = new Long[entity.getByServiceOrg().size()];
				int i = 0;
				for (Organization org : entity.getByServiceOrg()) {
					if(org!=null){
						byOrgNos[i] = org.getOrgNo();
						i++;
					}
				}
				dto.setByServicesNos(byOrgNos);
			}
			if (entity.getRulePackage() != null) {
				dto.setRulePackageNo(entity.getRulePackage().getRulePackageNo());
			}
		} catch (Exception ex) {
			throw new ApplicationException(ex);
			
		}
	}

	/**
	 * 根据ID查找SLA信息
	 * @param no SLA编号
	 * @return SLAContractDTO
	 */
	@Transactional
	public SLAContractDTO findById(Long no) {

		SLAContract entity = slaContractDAO.findById(no);
		SLAContractDTO dto = new SLAContractDTO();

		if (entity != null) {
			entity2dto(entity, dto);
		}

		return dto;

	}

	/**
	 * 分页查找数据.
	 * @param queryDTO 查询DTO
	 * @param start 开始数据行
	 * @param limit 每页数据条数
	 * @return PageDTO 分页数据
	 */
	@SuppressWarnings("unchecked")
	@Transactional
	public PageDTO findSLAContractByPager(SLAContractQueryDTO queryDTO,
			int start, int limit, String sidx, String sord) {
		if (queryDTO.getOrgNos() != null && queryDTO.getOrgNos().length > 0) {
			queryDTO.setOrgNos(organizationService.reverFindOrg(queryDTO
					.getOrgNos()));
		}
		PageDTO p = slaContractDAO
				.findPager(queryDTO, start, limit, sidx, sord);
		List<SLAContract> entities = p.getData();
		List<SLAContractDTO> dtos = new ArrayList<SLAContractDTO>(
				entities.size());
		for (SLAContract entity : entities) {
			SLAContractDTO dto = new SLAContractDTO();
			entity2dto(entity, dto);
			dtos.add(dto);
		}
		p.setData(dtos);
		return p;
	}
	
	/**
	 * 查找所有的SLA协议
	 * @return List<SLAContractDTO>
	 */
	@Transactional
	public List<SLAContractDTO> findAllSLAContract(){
		List<SLAContract> entities = slaContractDAO.findAll();
		List<SLAContractDTO> dtos = new ArrayList<SLAContractDTO>(
				entities.size());
		for (SLAContract entity : entities) {
			SLAContractDTO dto = new SLAContractDTO();
			entity2dto(entity, dto);
			dtos.add(dto);
		}
		return dtos;
	}

	/**
	 * 根据SLA编号查找被服务机构编号数组.
	 * 
	 * @param contractNo SLA编号
	 * @return Long [] 被服务机构编号数组
	 */
	@Transactional
	public Long[] findByServicesNosByContractNo(Long contractNo) {
	    Long[] servicesNos = null;
		SLAContract sc = slaContractDAO.findById(contractNo);

		if (sc != null && sc.getByServiceOrg() != null) {

			servicesNos = new Long[sc.getByServiceOrg().size()];

			int i = 0;
			for (Organization og : sc.getByServiceOrg()) {

				servicesNos[i] = og.getOrgNo();
				i++;
			}

		}

		return servicesNos;

	}

	/**
	 * 根据SLA编号查找关联服务
	 * 
	 * @param contractNo SLA编号
	 * @return Long[] 
	 */
	@Transactional
	public Long[] findByServicesDirNosByContractNo(Long contractNo) {
		Long[] longs = null;
		SLAContract sc = slaContractDAO.findById(contractNo);
		if (sc != null && sc.getServiceDirs() != null) {
			Long[] servicesNos = new Long[sc.getServiceDirs().size()];
			int i = 0;
			for (EventCategory ec : sc.getServiceDirs()) {
				servicesNos[i] = ec.getEventId();
				i++;
			}
			longs = servicesNos;
		}
		return longs;
	}

	/**
	 * 保存（修改）SLA信息
	 * @param dto
	 */
	@Transactional
	public void mergeSLAContract(SLAContractDTO dto) {
		SLAContract entity = slaContractDAO.findById(dto.getContractNo());
		dto2entity(dto, entity);
		if (dto.getServiceOrgNo() != null) {
			OrganizationServices serviceOrg = organizationServicesDAO.findById(dto.getServiceOrgNo());
			if (serviceOrg != null) {
				ServiceTime st = serviceTimeDAO.findByOrgNo(serviceOrg.getOrgNo());
				if (st != null) {
					if (!st.isAlreadySetWorkWeek()){
						throw new ApplicationException("ERROR_WORKING_DAYS_NOT_SET");
					}
				} else {
					throw new ApplicationException("ERROR_WORKING_DAYS_NOT_SET");
				}
			}
			entity.setServiceOrg(serviceOrg);
		}
		// 设置被服务机构
		if (dto.getByServicesNos() != null && dto.getByServicesNos().length > 0) {
			Long[] servicesNos = dto.getByServicesNos();
			Set<Organization> byServices = new HashSet<Organization>();
			for (int i = 0; i < servicesNos.length; i++) {
				if (servicesNos[i] != null) {
					byServices.add(organizationDAO.findById(servicesNos[i]));
				}
			}
			if (byServices.size() > 0) {
				entity.setByServiceOrg(new ArrayList<Organization>(byServices));
			}
		}
		// 设置被服务机构
		if (dto.getServiceDirNos() != null && dto.getServiceDirNos().length > 0) {
			Long[] servicesNos = dto.getServiceDirNos();
			Set<EventCategory> serviceDir = new HashSet<EventCategory>();
			for (int i = 0; i < servicesNos.length; i++) {
				if (servicesNos[i] != null) {
					serviceDir.add(eventCategoryDAO.findById(servicesNos[i]));
				}
			}
			if (serviceDir.size() > 0) {
				entity.setServiceDirs(new ArrayList<EventCategory>(serviceDir));
			}
		}
		slaContractDAO.merge(entity);
	}

	/**
	 * getOrgChildren
	 * @param parentNo
	 * @param byServices
	 */
	private void getOrgChildren(Long parentNo, Set<Organization> byServices) {
		List<Organization> childrens = organizationDAO.findByParent(parentNo);
		if (childrens != null) {
			for (Organization og : childrens) {
				byServices.add(og);
				// 递归
				getOrgChildren(og.getOrgNo(), byServices);
			}
		}
	}

	/**
	 * getServieDirChildren
	 * @param parentNo
	 * @param serviceDirs
	 */
	private void getServieDirChildren(Long parentNo,
			Set<EventCategory> serviceDirs) {
		List<EventCategory> childrens = eventCategoryDAO.findByParent(parentNo);
		if (childrens != null) {
			for (EventCategory og : childrens) {
				serviceDirs.add(og);
				// 递归
				getServieDirChildren(og.getEventId(), serviceDirs);
			}
		}
	}

	/**
	 * 根据ID删除SLA
	 * @param no SLA编号
	 * @return boolean 是否删除成功
	 */
	@Transactional
	public boolean removeSLAContract(Long no) {

		boolean result = true;
		Byte delete = 1;
		SLAContract slaContract = slaContractDAO.findById(no);
		RulePackage rp = slaContract.getRulePackage();
		if (slaContract.getDataFlag().equals(delete)) {
			result = false;
		} else {

			// 删除包
			if (rp != null) {
				rulePackageDAO.delete(rp);
			}
			// 删除SLA
			slaContractDAO.delete(slaContract);
		}

		return result;

	}

	/**
	 * 批量删除SLA
	 * @param nos SLA
	 * @return boolean
	 */
	@Transactional
	public boolean removeSLAContracts(Long[] nos) {

		boolean result = true;
		Byte delete = 1;
		for (Long id : nos) {
			SLAContract slaContract = slaContractDAO.findById(id);
			if (slaContract.getDataFlag().equals(delete)) {
				result = false;
			}
		}
		if (result) {
			// 删除对应的包
			for (int i = 0; i < nos.length; i++) {

				SLAContract slaContract = slaContractDAO.findById(nos[i]);
				RulePackage rp = slaContract.getRulePackage();

				if (rp != null) {// 删除包
					rulePackageDAO.delete(rp);
				}

				// 删除SLA
				slaContractDAO.delete(slaContract);
			}
		}

		return result;

	}

	/**
	 * 保存SLA
	 * 
	 * @param dto
	 */
	@Transactional
	public void saveSLAContract(SLAContractDTO dto) {
		SLAContract entity = new SLAContract();
		dto2entity(dto, entity);
		if (dto.getServiceOrgNo() != null) {
			OrganizationServices serviceOrg = organizationServicesDAO
					.findById(dto.getServiceOrgNo());
			if (serviceOrg != null) {
				ServiceTime st = serviceTimeDAO.findByOrgNo(serviceOrg.getOrgNo());
				if (st != null) {
					if (!st.isAlreadySetWorkWeek()) {
						throw new ApplicationException("ERROR_WORKING_DAYS_NOT_SET");
					}
				} else {
					throw new ApplicationException("ERROR_WORKING_DAYS_NOT_SET");
				}
			}
			entity.setServiceOrg(serviceOrg);
		}
		// 设置被服务机构
		if (dto.getByServicesNos() != null && dto.getByServicesNos().length > 0) {
			Long[] servicesNos = dto.getByServicesNos();
			Set<Organization> byServices = new HashSet<Organization>();
			for (int i = 0; i < servicesNos.length; i++) {
				if (servicesNos[i] != null) {
					byServices.add(organizationDAO.findById(servicesNos[i]));
					// 递归查找子类
					getOrgChildren(servicesNos[i], byServices);
				}
			}
			if (byServices.size() > 0) {
				entity.setByServiceOrg(new ArrayList<Organization>(byServices));
			}
		}
		// 设置被服务机构
		if (dto.getServiceDirNos() != null && dto.getServiceDirNos().length > 0) {

			Long[] servicesNos = dto.getServiceDirNos();

			Set<EventCategory> serviceDir = new HashSet<EventCategory>();

			for (int i = 0; i < servicesNos.length; i++) {

				if (servicesNos[i] != null) {

					serviceDir.add(eventCategoryDAO.findById(servicesNos[i]));
					// 递归查找子类
					getServieDirChildren(servicesNos[i], serviceDir);
				}
			}
			if (serviceDir.size() > 0) {
				entity.setServiceDirs(new ArrayList<EventCategory>(serviceDir));
			}
		}

		String packageName = "com.drools.drl." + RandomLetters.getWord();

		RulePackage rulepackage = new RulePackage();
		rulepackage.setPackageName(packageName);
		rulepackage.setImports("com.wstuo.itsm.request.dto.RequestDTO;");
		rulepackage.setLocation(new Date().getTime() + ".drl");
		rulePackageDAO.save(rulepackage);

		RulePackage rp = rulePackageDAO
				.findUniqueBy("packageName", packageName);

		entity.setRulePackage(rp);

		slaContractDAO.save(entity);
		dto.setContractNo(entity.getContractNo());

		addDefaultSLARule(entity);

	}

	/**
	 * 添加默认的SLA规则
	 * @param contract
	 */
	private void addDefaultSLARule(SLAContract contract) {

		LanguageContent languageContent = LanguageContent.getInstance();
		// 添加默认SLA规则
		SLARule slaRule = new SLARule();

		slaRule.setRuleName(languageContent
				.getContent("SLAContractService.addDefaultSLARule.GivenName"));
		slaRule.setSalience(100L);// 默认为100

		slaRule.setDataFlag(((Number) 1).byteValue());

		// 2小时响应
		slaRule.setRday(0);
		slaRule.setRhour(2);
		slaRule.setRminute(0);

		// 4小时响应
		slaRule.setFday(0);
		slaRule.setFhour(4);
		slaRule.setFminute(0);

		slaRule.setResponseRate(95D);
		slaRule.setCompleteRate(90D);

		slaRule.setIncludeHoliday(true);
		slaRule.setDialect("mvel");

		// 动作
		List<RuleAction> actions = new ArrayList<RuleAction>(1);
		RuleAction action = new RuleAction();
		action.setGivenName(languageContent
				.getContent("SLAContractService.addDefaultSLARule.GivenName"));
		action.setGivenValue(languageContent
				.getContent("SLAContractService.addDefaultSLARule.GivenName"));

		action.setPropertyName("matchRuleName");
		action.setActionName("matchRuleName");
		action.setRule(slaRule);

		action.setDataFlag(((Number) 1).byteValue());
		action.setSequence(0);
		actions.add(action);
		slaRule.setActions(actions);

		// 空的条件
		RulePattern pattern = new RulePattern();
		pattern.setConstraints(new ArrayList<RuleConstraint>());
		pattern.setPatternBinding("dto");
		pattern.setPatternType("RequestDTO");

		slaRule.setCondition(pattern);

		slaRule.setRulePackage(contract.getRulePackage());// 所属包
		slaRule.setSlaContract(contract);

		// 包下添加此规则
		List<Rule> rules = new ArrayList<Rule>(1);
		rules.add(slaRule);
		contract.getRulePackage().setRules(rules);

		// 打印规则
		slaRuleDAO.save(slaRule);

		procreationDrlFiles.printDrlFiles(slaRule);

	}

	/**
	 * 加载默认SLA.
	 */
	@Transactional
	public void defaultSLAContract() {
		SLAContract entity = new SLAContract();
		LanguageContent languageContent = LanguageContent.getInstance();
		entity.setContractName(languageContent
				.getContent("SLAContractService.defaultSLAContract.ContractName"));
		entity.setAgreement(languageContent
				.getContent("SLAContractService.defaultSLAContract.ContractName"));
		entity.setVersionNumber("1.0");
		entity.setBeginTime(new Date());
		entity.setEndTime(new GregorianCalendar(Calendar.getInstance().get(Calendar.YEAR)+2, 01, 01, 00, 00, 00)
				.getTime());
		entity.setDataFlag((byte) 1);
		entity.setIsDefault(true);
		// 服务机构
		OrganizationServices serviceOrg = organizationServicesDAO.findUniqueBy(
				"orgName", "Helpdesk");
		entity.setServiceOrg(serviceOrg);

		// 被服务机构
		List<Organization> byServices = organizationDAO.findAll();
		entity.setByServiceOrg(byServices);
		String packageName = "com.drools.drl." + RandomLetters.getWord();
		RulePackage rulepackage = new RulePackage();
		rulepackage.setPackageName(packageName);
		rulepackage.setImports("com.wstuo.itsm.request.dto.RequestDTO;");
		rulepackage.setLocation(new Date().getTime() + ".drl");
		rulepackage = rulePackageDAO.merge(rulepackage);
		entity.setRulePackage(rulepackage);
		slaContractDAO.save(entity);
		addDefaultSLARule(entity);
	}

	/**
	 * 取得默认的规则包.
	 * @return RulePackage
	 */
	private RulePackage getDefaultRulePackage() {

		String packageName = "com.drools.drl." + RandomLetters.getWord();

		RulePackage rulepackage = new RulePackage();
		rulepackage.setPackageName(packageName);
		rulepackage.setImports("com.wstuo.itsm.request.dto.RequestDTO;");
		rulepackage.setLocation(new Date().getTime() + ".drl");
		rulePackageDAO.save(rulepackage);

		RulePackage rp = rulePackageDAO
				.findUniqueBy("packageName", packageName);

		return rp;

	}

	/**
	 * 导入CSV.
	 * 
	 * @param importFilePath
	 * @return String
	 */
	@Transactional
	public String importSLA(String importFilePath) {
		String result = "success";
		try {
			String fileEncode = FileEncodeUtils.getFileEncode(new File(importFilePath));
			Reader rd = new InputStreamReader(new FileInputStream(
					importFilePath), fileEncode);// 以字节流方式读取数据
			CSVReader reader = new CSVReader(rd);
			String[] line = null;

			while ((line = reader.readNext()) != null) {

				SLAContract sc = new SLAContract();

				if (slaContractDAO.findById(Long.parseLong(line[0])) == null) {

					sc.setContractNo(Long.parseLong(line[0]));
					sc.setContractName(line[1]);
					sc.setVersionNumber(line[2]);
					sc.setBeginTime(TimeUtils.parse(line[3],TimeUtils.DATETIME_PATTERN));
					sc.setEndTime(TimeUtils.parse(line[4],TimeUtils.DATETIME_PATTERN));
					sc.setAgreement(line[5]);
					//所属包
					if (StringUtils.hasText(line[6])) {
						sc.setRulePackage(rulePackageDAO.findById(Long.parseLong(line[6])));// 查找规则包
					} else {
						sc.setRulePackage(getDefaultRulePackage());// 默认添加规则包
					}

					if (StringUtils.hasText(line[7])) {
						sc.setServiceOrg(getOrganizationServicesByNoStr(line[7]));// 获取服务机构
					}
					if (StringUtils.hasText(line[8])) {
						sc.setByServiceOrg(getOrganizationsByArrStr(line[8]));// 取得被服务机构
					}

					// 数据标识
					if (StringUtils.hasText(line[9])) {
						sc.setDataFlag(Byte.parseByte(line[9]));
					}

					slaContractDAO.save(sc);

				} else {
					result = "fall";
					break;
				}
			}

		} catch (Exception ex) {
			LOGGER.error(ex);
			result = "fall";
		}
		return result;
	}

	/**
	 * 导出CSV.
	 * @param qdto SLAContractQueryDTO
	 * @return InputStream
	 */
	@Transactional
	public InputStream exportSLA(SLAContractQueryDTO qdto) {

		List<String[]> data = new ArrayList<String[]>();

		LanguageContent lc = LanguageContent.getInstance();

		data.add(new String[] { lc.getContent("common.id"),
				lc.getContent("label.role.roleName"),
				lc.getContent("label.release.version"),
				lc.getContent("label.orgSettings.startTime"),
				lc.getContent("label.sla.slaEndTime"),
				lc.getContent("label.sla.slaServiceAgreement"),
				lc.getContent("label_sla_isDefault"),
				lc.getContent("label.sla.rulePackageNo"),
				lc.getContent("label.sla.serviceOrgNo"),
				lc.getContent("title.sla.byServiceOrg"),
				lc.getContent("label.sla.dataFlag") });// 加入表头

		// 升序排列
		PageDTO p = slaContractDAO.findPager(qdto, 0, CSVWriter.EXPORT_SIZE,
				"contractNo", "desc");
		@SuppressWarnings("unchecked")
		List<SLAContract> entities = (List<SLAContract>) p.getData();
		String rulePackageNo = "";
		String serviceOrgNo = "";
		String startTime = "00:00";
		String IsDefault = lc.getContent("label.dynamicReports.no");
		for (SLAContract sla : entities) {

			if (sla.getRulePackage() != null
					&& sla.getRulePackage().getRulePackageNo() != null) {// 包
				rulePackageNo = sla.getRulePackage().getPackageName();
			}

			if (sla.getServiceOrg() != null
					&& sla.getServiceOrg().getOrgNo() != null) {// 服务机构
				serviceOrgNo = sla.getServiceOrg().getOrgName();
			}
			if (sla.getIsDefault() != null && sla.getIsDefault())
				IsDefault = lc.getContent("label.dynamicReports.yes");
			if (sla.getBeginTime() != null)
				startTime = TimeUtils.format(sla.getBeginTime(),TimeUtils.DATETIME_PATTERN);
			data.add(new String[] { sla.getContractNo() + "",
					sla.getContractName() + "", sla.getVersionNumber(),
					startTime, TimeUtils.format(sla.getEndTime(),TimeUtils.DATETIME_PATTERN), sla.getAgreement(),
					IsDefault, rulePackageNo, serviceOrgNo,
					getByServiceOrgNos(sla).substring(1),
					sla.getDataFlag().toString() });
		}

		StringWriter sw = new StringWriter();
		CSVWriter csvw = new CSVWriter(sw);
		csvw.writeAll(data);

		ByteArrayInputStream stream = null;
		stream = new ByteArrayInputStream(sw.getBuffer().toString().getBytes());
		return stream;

	}


	/**
	 * 根据SLA取得被服务机构字符串.
	 * @param sc
	 * @return String
	 */
	private String getByServiceOrgNos(SLAContract sc) {

		StringBuffer byServiceOrgName = new StringBuffer();

		if (sc != null && sc.getByServiceOrg() != null
				&& sc.getByServiceOrg().size() > 0) {

			for (Organization org : sc.getByServiceOrg()) {

				byServiceOrgName.append(",").append( org.getOrgName() );
			}
		}
		return byServiceOrgName.toString();
	}

	/**
	 * 根据机构字串获取服务机构.
	 * 
	 * @param noStr
	 * @return OrganizationServices
	 */
	private OrganizationServices getOrganizationServicesByNoStr(String noStr) {

		try {
			Long no = Long.parseLong(noStr);
			return organizationServicesDAO.findById(no);
		} catch (NumberFormatException ex) {
			throw new ApplicationException("ERROR_NUMBERFORMAT\n" + ex, ex);
		}
	}

	/**
	 * 根据字串获取被服务机构列表.
	 * @param arrStr
	 * @return List<Organization>
	 */
	private List<Organization> getOrganizationsByArrStr(String arrStr) {

		List<Organization> orgList = new ArrayList<Organization>();

		String[] arrString = arrStr.split(",");
		for (String s : arrString) {

			if (!"".equals(s)) {
				orgList.add(getOrganizationByNoStr(s));
			}
		}
		return orgList;
	}

	/**
	 * 根据机构字串获取机构.
	 * @param noStr
	 * @return Organization
	 */
	private Organization getOrganizationByNoStr(String noStr) {

		try {
			Long no = Long.parseLong(noStr);
			return organizationDAO.findById(no);
		} catch (NumberFormatException ex) {

			throw new ApplicationException("ERROR_NUMBERFORMAT\n" + ex, ex);
		}
	}
	
	

}